package paypal

import (
	"encoding/json"
	"net/http"
	"regexp"

	"github.com/plutov/paypal"
)

// get pay link to pay.
func PaypalOrderRequest(w http.ResponseWriter, r *http.Request) {
	sAmount := r.PostForm.Get("Amount")
	if len(sAmount) == 0 {
		w.Write([]byte(InvalidAmount))
		return
	}
	isNumber, _ := regexp.MatchString(sAmount, "0123456789")
	if !isNumber {
		w.Write([]byte(EmptyAmount))
		return
	}

	purchases := make([]paypal.PurchaseUnitRequest, 1)
	purchases[0] = paypal.PurchaseUnitRequest{
		Amount: &paypal.PurchaseUnitAmount{
			Currency: "USD",
			Value:    sAmount,
		},
	}
	payer := &paypal.CreateOrderPayer{}
	appContext := &paypal.ApplicationContext{
		ReturnURL: "xxx", // pay link
		CancelURL: "",
	}
	order, err := DefaultPayPal().GetClient().CreateOrder("CAPTURE", purchases, payer, appContext)
	if err != nil {
		w.Write([]byte(CreaterOrderFail))
		return
	}

	orderData := struct {
		PayHref string
		OrderNo string
	}{
		PayHref: order.Links[1].Href,
		OrderNo: order.ID,
	}

	rsp, err := json.Marshal(orderData)
	if err != nil {
		w.Write([]byte(UnKnowError))
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Write(rsp)
	return
}

//pay over call back notify receiver account.
func PayPalOver(w http.ResponseWriter, r *http.Request) {
	sOrder := r.PostForm.Get("Order")
	if len(sOrder) == 0 {
		w.Write([]byte(InvalidOrder))
		return
	}
	order, err := DefaultPayPal().GetClient().CaptureOrder(sOrder, paypal.CaptureOrderRequest{})
	if err != nil {
		w.Write([]byte(CaptureOrderFail))
		return
	}
	if (*order).Status != "COMPLETED" {
		w.Write([]byte(PayOrderFail))
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Write([]byte(Success))
}
